package com.wormhole.wormholemanagement.service;

import com.wormhole.wormholemanagement.entity.Operator;
import com.wormhole.wormholemanagement.repository.OperatorRepository;
import com.wormhole.wormholemanagement.utils.OperatorDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class OperatorDetailsService implements UserDetailsService {

    private final OperatorRepository operatorRepository;

    @Autowired
    public OperatorDetailsService(OperatorRepository operatorRepository) {
        this.operatorRepository = operatorRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Operator operator = operatorRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));

//        return User.builder()
//                .username(operator.getUsername())
//                .password(operator.getPassword())
//                .roles(operator.getRole()) // 确保角色格式为 "ADMIN" 而不是 "ROLE_ADMIN"
//                .build();
        return new OperatorDetails(operator.getUsername(), operator.getPassword(), operator.getOperatorId());
    }
}